﻿using System;
using UnityEditor.MemoryProfiler;
using UnityEngine;

namespace PerfAssist.MemoryProfilerAdvanced.Editor.PAContrib
{
    public class MemSnapshotInfo
    {
        public int _totalCount;
        public int _totalSize;
        public CrawledMemorySnapshot Unpacked { get; private set; }

        public int TotalCount
        {
            get { return _totalCount; }
        }

        public int TotalSize
        {
            get { return _totalSize; }
        }

        public bool AcceptSnapshot(PackedMemorySnapshot packed)
        {
            _totalCount = 0;
            _totalSize = 0;

            try
            {
                MemUtil.LoadSnapshotProgress(0.01f, "crawling");
                var crawled = new Crawler().Crawl(packed);

                MemUtil.LoadSnapshotProgress(0.7f, "unpacking");
                Unpacked = CrawlDataUnpacker.Unpack(crawled);

                MemUtil.LoadSnapshotProgress(0.9f, "populating");
                foreach (var thing in Unpacked.allObjects)
                {
                    _totalSize += thing.size;
                    _totalCount++;
                }

                MemUtil.LoadSnapshotProgress(1.0f, "done");
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                Unpacked = null;
                return false;
            }

            return true;
        }
    }
}